package com.chiyi.controller;

import com.chiyi.bean.TOrder;
import com.chiyi.mapper.TOrderMapper;
import com.chiyi.transaction.OrderServiceTrans;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @date 2021/5/14 20:23
 */
@RestController
@Api(tags = "消息发送")
@RequestMapping("/message")
@Slf4j
public class RocketMQController {

    @Resource
    private RocketMQTemplate rocketMQTemplate;
    @Resource
    private OrderServiceTrans orderServiceTrans;
    @Resource
    private TOrderMapper tOrderMapper;

    @GetMapping("/syncSend")
    @ApiOperation("可靠同步发送消息")
    public Object syncSend() {
        SendResult sendResult = rocketMQTemplate
                .syncSend("test-topic-1:tag", "这是一个可靠同步信息");
        return sendResult;
    }

    @GetMapping("/asyncSend")
    @ApiOperation("可靠异步发送消息")
    public String asyncSend() {
        rocketMQTemplate
                .asyncSend("test-topic-2:tag", "这是一个可靠异步发送消息", new SendCallback() {
                    @Override
                    public void onSuccess(SendResult sendResult) {
                        log.info("-----发送成功---->>{}", sendResult);
                    }

                    @Override
                    public void onException(Throwable throwable) {
                        log.info("-----发送失败---->>{}", throwable.toString());
                    }
                });
        return "success";
    }

    @GetMapping("/oneWay")
    @ApiOperation("单向发送消息")
    public String oneWay() {
        rocketMQTemplate.sendOneWay("test-topic-3:tag", "这是一个单向发送信息");
        return "success";
    }

    @GetMapping("/testSyncSendOrder")
    @ApiOperation("顺序消息")
    public String testSyncSendOrder() {
        for (int i = 0; i < 10; i++) {
            rocketMQTemplate.syncSendOrderly("test-topic-4:tag", "顺序消息" + i, "keyOrder");
        }
        return "success";
    }

    @GetMapping("/orderTrans/{id}")
    @ApiOperation("发送事务")
    public String orderTrans(@PathVariable Integer id) {
        TOrder tOrder = tOrderMapper.selectById(id);
        orderServiceTrans.createOrderBefore(tOrder);
        return "success";
    }


}
